package com.zl.controller;

import com.jcraft.jsch.JSchException;
import com.zl.service.LogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author zhoul
 * @since 2016-09-19-15:46
 */

public class LogWebSocketHandler extends TextWebSocketHandler {
    private static final Logger log = LoggerFactory.getLogger(LogWebSocketHandler.class);
    private final LogService service;

    public LogWebSocketHandler(LogService service) {
        this.service = service;
    }

    /**
     * 建立连接后
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("afterConnectionEstablished");
    }

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message)
            throws Exception {
        String path = message.getPayload();
        log.info("handleTextMessage " + path + " " + session);
        try {
            service.showLog("root", "hadoop", "192.168.174.128", path, session);
        } catch (JSchException | IOException e) {
            session.sendMessage(new TextMessage(e.getMessage()));
        }
    }

    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        service.closeInputStreamAndChannel(session);
    }
}
